﻿using BigMonitoringWarningApi.Model.ApiResult;
using GYCTOAManagementSystem.Models.Enum;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Model.ViewModel;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class RightController : Controller
    {
        DBContext db;
        Message mes;
        GlobalPublic globalPublic;
        PublicTool PublicTool;
        IWebHostEnvironment _webHostEnvironment;
        //权限管理
        public RightController(IWebHostEnvironment webHostEnvironment, DBContext _db, Message _mes, GlobalPublic _globalPublic)
        {
            db = _db;
            mes = _mes;
            globalPublic = _globalPublic;
            PublicTool = new PublicTool(_db);
            _webHostEnvironment = webHostEnvironment;
        }

        #region OA单据审批规则
        /// <summary>
        /// 更新审批规则
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("UpdateAuditRuleBit")]
        public JsonResult UpdateAuditRuleBit(int id = -1)
        {
            var obj = db.AuditRule.Find(id);
            mes.IsSuccess = true;
            if (obj == null)
            {
                mes.IsSuccess = false;
                mes.Msg = "该记录不存在";
            }
            return new JsonResult(new { obj = obj, mes = mes });
        }
        /// <summary>
        /// 展示审批规则
        /// </summary>
        /// <returns></returns>
        private JsonResult ShowAuditRule(string ModuleNumber)
        {
            var obj = db.AuditRule.Where(x => x.ModuleNumber == ModuleNumber && !x.Delete && !x.IsRevoke).ToList();
            return new JsonResult(obj);
        }

        /// <summary>
        /// 获取审批规则数据
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetAuditRuleDetail")]
        public JsonResult GetAuditRuleDetail([FromBody] dynamic formData)
        {
            //  int limit, int offset, AuditRule auditRule, DateTime? Start, DateTime? End)
            #region 条件拼接
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var Start = Convert.ToString(jsondata["from"]["Start"]);
            var End = Convert.ToString(jsondata["from"]["End"]);
            var ModuleNumber = Convert.ToString(jsondata["from"]["ModuleNumber"]);
            int offset = Convert.ToInt32(jsondata["currentPage"].ToString());
            int limit = Convert.ToInt32(jsondata["pagesize"].ToString());
            #endregion
            #region 构造搜索条件
            var sql = "select * from AuditRule where 1=1 ";
            if (!string.IsNullOrWhiteSpace(Start))
            {
                sql += "and OperatDate>='" + Start + "' ";
            }
            if (!string.IsNullOrWhiteSpace(End))
            {
                sql += "and OperatDate<='" + End + "' ";
            }
            if (!string.IsNullOrEmpty(ModuleNumber))
            {
                sql += "and ModuleNumber like '%" + ModuleNumber + "%' ";
            }
            #endregion

            var list = db.AuditRule.FromSqlRaw(sql).Where(x => !x.Delete && !x.IsRevoke).OrderByDescending(x => x.ModuleNumber).ThenBy(x => x.OperatDate).ToList();
            var total = list.Count;
            var rows = list.Skip(limit * (offset - 1)).Take(limit).ToList();
            return new JsonResult(new { code = 0, msg = "", count = total, data = rows });
        }
        /// <summary>
        /// 新增审批规则
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("AddAuditRule")]
        public JsonResult AddAuditRule([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var auditRule = JsonConvert.DeserializeObject<AuditRule>(jsondata["AddAuditRuleDB"].ToString());
            Message message = new Message();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            using (var scope = new TransactionScope())
            {
                if (auditRule.AuditUserId1 != 0)
                    auditRule.AuditPeopleNumber++;
                if (auditRule.AuditUserId2 != 0)
                    auditRule.AuditPeopleNumber++;
                if (auditRule.AuditUserId3 != 0)
                    auditRule.AuditPeopleNumber++;
                if (auditRule.AuditUserId4 != 0)
                    auditRule.AuditPeopleNumber++;
                if (auditRule.AuditUserId5 != 0)
                    auditRule.AuditPeopleNumber++;
                if (auditRule.AuditUserId6 != 0)
                    auditRule.AuditPeopleNumber++;
                auditRule.OperatId = userid;
                auditRule.OperatDate = DateTime.Now;
                db.AuditRule.Add(auditRule);
                message.IsSuccess = db.SaveChanges() > 0;
                //提交事务
                scope.Complete();
            }
            message.Msg = message.IsSuccess ? "添加成功" : "添加失败";
            return new JsonResult(message);
        }

        /// <summary>
        /// 更新审批规则
        /// </summary>
        /// <param name="finance"></param>
        /// <returns></returns>
        [HttpPost("UpdateAuditRule")]
        public JsonResult UpdateAuditRule([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var auditRule = JsonConvert.DeserializeObject<AuditRule>(jsondata["UpAuditRuleDB"].ToString());

            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            Message mes = new Message();
            AuditRule newauditRule = db.AuditRule.Find(auditRule.Id);
            auditRule.AuditPeopleNumber = 0;
            if (auditRule.AuditUserId1 != 0)
                auditRule.AuditPeopleNumber++;
            if (auditRule.AuditUserId2 != 0)
                auditRule.AuditPeopleNumber++;
            if (auditRule.AuditUserId3 != 0)
                auditRule.AuditPeopleNumber++;
            if (auditRule.AuditUserId4 != 0)
                auditRule.AuditPeopleNumber++;
            if (auditRule.AuditUserId5 != 0)
                auditRule.AuditPeopleNumber++;
            if (auditRule.AuditUserId6 != 0)
                auditRule.AuditPeopleNumber++;
            newauditRule.ModuleNumber = auditRule.ModuleNumber;
            newauditRule.SponsorUser = auditRule.SponsorUser;
            newauditRule.SponsorDepart = auditRule.SponsorDepart;
            newauditRule.AuditUserId1 = auditRule.AuditUserId1;
            newauditRule.AuditUserId2 = auditRule.AuditUserId2;
            newauditRule.AuditUserId3 = auditRule.AuditUserId3;
            newauditRule.AuditUserId4 = auditRule.AuditUserId4;
            newauditRule.AuditUserId5 = auditRule.AuditUserId5;
            newauditRule.AuditUserId6 = auditRule.AuditUserId6;
            newauditRule.AuditPeopleNumber = auditRule.AuditPeopleNumber;
            newauditRule.CCPerson = auditRule.CCPerson;
            newauditRule.OperatId = userid;
            newauditRule.OperatDate = DateTime.Now;
            mes.IsSuccess = db.SaveChanges() > 0 ? true : false;
            mes.Msg = mes.IsSuccess ? "更新成功" : "更新失败";
            return new JsonResult(mes);
        }
        /// <summary>
        /// 删除审批规则
        /// </summary>
        /// <param name="arrDel">id集合</param>
        /// <returns></returns>
        [HttpPost("DeleteAuditRule")]
        public JsonResult DeleteAuditRule(int[] arrDel)
        {
            Message mes = new Message();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            foreach (var t in arrDel)
            {
                var obj = db.AuditRule.Find(t);
                if (obj != null)
                {
                    obj.Delete = true;
                    obj.OperatId = userid;
                    obj.OperatDate = DateTime.Now;
                }
            }
            mes.IsSuccess = db.SaveChanges() > 0;
            mes.Msg = mes.IsSuccess ? "删除成功" : "删除失败";
            return new JsonResult(mes);
        }
        /// <summary>
        /// 删除审批规则
        /// </summary>
        /// <param name="formData">   </param>
        /// <returns></returns>
        [HttpPost("RevokeAuditRule")]
        public JsonResult RevokeAuditRule([FromBody] dynamic formData)
        {
            // int Id)
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var Id = Convert.ToInt32(jsondata["Id"]);
            Message mes = new Message();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var obj = db.AuditRule.Find(Id);
            if (obj != null)
            {
                obj.IsRevoke = true;
                obj.OperatId = userid;
                obj.OperatDate = DateTime.Now;
            }
            mes.IsSuccess = db.SaveChanges() > 0;
            mes.Msg = mes.IsSuccess ? "撤销成功" : "撤销失败";
            return new JsonResult(new { mes = mes });
        }
        #endregion

        #region 系统设置

        /// <summary>
        /// 获取所有的系统设置数据
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost("GetSystemDb")]
        public JsonResult GetSystemDb()
        {
            var oaList = db.QuartZShortMessageModel.Where(x=>!x.Delete).ToList();
            return new JsonResult(new { data = oaList });
        }

        [HttpPost("UpQuartZShortMessageModel")]
        public JsonResult UpQuartZShortMessageModel([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var quart = Convert.ToString(jsondata["quart"]);
            var bol = false;
            try
            {
                List<QuartZShortMessageModel> user = JsonConvert.DeserializeObject<List<QuartZShortMessageModel>>(quart);
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

                using (var scope = new TransactionScope())
                {
                    for (int i = 0; i < user.Count(); i++)
                    {
                        var newdb = db.QuartZShortMessageModel.Where(x => x.Id == user[i].Id).FirstOrDefault();
                        if (newdb==null && user[i].Id==0)
                        {
                            PublicTool.GetOpDataOpId(user[i], author);
                            db.QuartZShortMessageModel.Add(user[i]);
                        }
                        else
                        {
                            newdb.Mileage = user[i].Mileage;
                            newdb.phone = user[i].phone;
                            newdb.StartDate = user[i].StartDate;
                            newdb.EndDate = user[i].EndDate;
                            newdb.WarningDay = user[i].WarningDay;
                            PublicTool.GetOpDataOpId(newdb, author);
                        }
                    }
                    bol = db.SaveChanges() > 0;
                    //提交事务
                    scope.Complete();
                }

            }
            catch (Exception ex)
            {
                throw;
            }
            return new JsonResult(new { bol = bol });
        }

        #endregion

        #region 钉钉内部ip与OA人员id对应
        [HttpPost("DingDingSame")]
        public JsonResult DingDingSame()
        {
            var userlis = db.Users.ToList();
            PublicTool.getuserlis();
            //for (int i = 0; i < userlis.Count; i++)
            //{
            //    userlis[i].DD_number = PublicTool.UserIdByName(userlis[i].UserName);
            //}
            bool result = db.SaveChanges() > 0;
            return new JsonResult(new { result = result });
        }
        #endregion

        #region 角色管理

        /// <summary>
        /// 获取所有的角色
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetAllRole")]
        public JsonResult GetAllRole()
        {
            List<Role> roles = db.Role.Where(x => !x.Delete).ToList();
            return new JsonResult(new { roles = roles });
        }



        /// <summary>
        /// 获取财务角色Id
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetFinancialId")]
        public JsonResult GetFinancialId()
        {
            var ids = ConfigurationHelper.GetConfigHeadRoleId("FinancialId");
            return new JsonResult(new { roleid = ids });
        }
        /// <summary>
        /// 获取项目负责人角色Id
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetHeadUserId")]
        public JsonResult GetHeadUserId()
        {
            var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            return new JsonResult(new { roleid = ids });
        }



        /// <summary>
        /// 获取项目员工角色Id
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetUserId")]
        public ApiResult GetUserId()
        {
            var ids = ConfigurationHelper.GetConfigHeadRoleId("UserId");
            return ApiResult.True(new { Userid = ids });
        }
        /// <summary>
        /// 写入财务角色Id
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SetHeadUserId")]
        public ApiResult SetHeadUserId([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var id = Convert.ToString(jsondata["id"]);
            new ConfigurationHelper().WriteJSON("HeadRoleId", id);
           return ApiResult.True();
        }

        /// <summary>
        /// 写入人员角色Id
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SetUserId")]
        public ApiResult SetserId([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var id = Convert.ToString(jsondata["id"]);
            new ConfigurationHelper().WriteJSON("UserId", id);
            return ApiResult.True();
        }

        /// <summary>
        /// 写入人员角色Id
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("SetFinancialId")]
        public ApiResult SetFinancialId([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var id = Convert.ToString(jsondata["id"]);
            new ConfigurationHelper().WriteJSON("FinancialId", id);
            return ApiResult.True();
        }


        /// <summary>
        /// 获取所有角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddRole")]                                                                     
        public JsonResult AddRole([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var name = Convert.ToString(jsondata["name"]);
            var duty = Convert.ToString(jsondata["duty"]);
            //string name, string duty)
            Role r = db.Role.Where(x => x.RoleName.Contains(name)).FirstOrDefault();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            if (r == null)
            {
                Role role = new Role();
                role.RoleName = name;
                role.RoleDuty = duty;
                PublicTool.GetOpDataOpId(role, author);
                db.Role.Add(role);
                mes.IsSuccess = db.SaveChanges() > 0;
                mes.Msg = "角色添加成功";
            }
            else
            {
                mes.IsSuccess = false;
                mes.Msg = "存在同名角色，无法添加！";
            }
            return new JsonResult(new { mes = mes });
        }

        /// <summary>
        /// 更新角色名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost("UpdateRoleName")]
        public JsonResult UpdateRoleName([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var rolestr = Convert.ToString(jsondata["role"]);
            // Role role)
            Role role = JsonConvert.DeserializeObject<Role>(rolestr);
            var c = role;
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            int r = db.Role.Where(x => x.RoleName == role.RoleName.Trim()).ToList().Count;
            if (r == 0)
            {
                Role ro = db.Role.Where(x => x.Id == role.Id).FirstOrDefault();
                ro.RoleName = role.RoleName;
                ro.RoleDuty = role.RoleDuty;
                PublicTool.GetOpDataOpId(ro, author);
                mes.IsSuccess = db.SaveChanges() > 0;
                mes.Msg = "角色修改成功";

            }
            else
            {
                mes.IsSuccess = false;
                mes.Msg = "存在同名角色，无法修改！";
            }
            return new JsonResult(new { mes = mes });

        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("DelRole")]
        public JsonResult DelRole(int Id)
        {
            //foreach (int i in Id)
            //{
            //var iid = Convert.ToInt32(Id);
            Role r = db.Role.Where(x => x.Id == Id).FirstOrDefault();
            r.Delete = true;
            //}
            mes.IsSuccess = db.SaveChanges() > 0;
            if (mes.IsSuccess)
            {
                mes.Msg = ("数据删除成功");
            }
            else
            {
                mes.Msg = ("数据删除失败");
            }

            return new JsonResult(new { mes = mes });
        }
        /// <summary>
        /// 获取所有角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetRole")]
        public JsonResult GetRole([FromBody] dynamic formData)
        {
            //string search, int offset, int limit)
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var search = Convert.ToString(jsondata["search"]);
            var offset = Convert.ToInt32(jsondata["offset"]);
            var limit = Convert.ToInt32(jsondata["limit"]);

            List<Role> roles = new List<Role>();
            roles = db.Role.Where(x => x.RoleName != "Admin" && x.RoleName.Contains(search)).ToList();
            var total = roles.Count;
            var rows = roles.Take(limit * offset).Skip(limit * (offset - 1)).ToList();
            return new JsonResult(new { code = 0, msg = "", count = total, data = rows });
        }
        /// <summary>
        /// 根据id获取角色信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        private JsonResult GetRoleById(int Id)
        {
            var role = db.Role.Where(x => x.Id == Id).FirstOrDefault();
            return new JsonResult(new { role = role });
        }
        /// <summary>
        /// 更新角色权限，权限分配模块
        /// </summary>
        /// <returns></returns>
        //[Authorize(Roles = "Admin")]

        [HttpPost("UpdateRole")]
        public JsonResult UpdateRole([FromBody] dynamic formData)
        {
            //Role role)
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var rolestr = Convert.ToString(jsondata["rolestr"]);
            Role role = JsonConvert.DeserializeObject<Role>(rolestr);

            var query = from roles in db.Role
                        where roles.Id == role.Id
                        select roles;
            var roleinfo = query.FirstOrDefault();
            if (role.RoleNumber == null)
            {
                role.RoleNumber = "未分配权限";
            }
            roleinfo.RoleNumber = role.RoleNumber;
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            PublicTool.GetOpDataOpId(roleinfo, author);
            int count = db.SaveChanges();
            if (count >= 1)
            {
                return new JsonResult(new { succeed = true });
            }
            else
            {
                return new JsonResult(new { succeed = true });
            }
        }
        #endregion

        #region 权限管理
        //[Authorize(Roles = "Admin")]
        // GET: Right
        [HttpPost("RightManage")]
        public JsonResult RightManage([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var stxtname = Convert.ToString(jsondata["txtname"]);

            var query = from role in db.Role
                        where role.RoleName.Contains(stxtname) && !role.Delete
                        select role;
            List<Role> roles = query.ToList();
            ////菜单返回给前台
            //var DictDataDB = DictData();
            return new JsonResult(new { roles = roles });/*, DictDataDB = DictDataDB*/
        }
        private JsonResult DelDataRightManage(string id)
        {
            // Security security = new Security();
            //从MongoDB获取数据权限
            //读取mongodb数据库 查询权限值拥有的菜单
            string strcon = ConfigurationManager.ConnectionStrings["mongo_con"].ConnectionString;
            MongoClient client = new MongoClient(strcon);
            var clientdb = client.GetDatabase("oalist");
            var collection = clientdb.GetCollection<BsonDocument>("data_tables");

            var filter = Builders<BsonDocument>.Filter.Eq("_id", new ObjectId(id));
            var yanse = collection.DeleteMany(filter);
            return new JsonResult(new { cod = yanse.DeletedCount });
        }

        /// <summary>
        /// 数据权限页面
        /// </summary>
        /// <returns></returns>
        [HttpGet("DataPermissions")]
        public JsonResult DataPermissions(string roid)
        {

            //查询权限列表
            //读取mongodb数据库 查询权限值拥有的菜单
            //string strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:mongo_con");
            ////string strcon = ConfigurationHelper.GetConfigValueByKey["mongo_con"].ConnectionString;
            //var client = new MongoClient(strcon);
            //var clientdb = client.GetDatabase("oalist");
            ////读取集合collection
            //var collection = clientdb.GetCollection<BsonDocument>("data_tables");
            //var data_authority = clientdb.GetCollection<BsonDocument>("data_authority");
            ////创建约束生成器
            //FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //// Dictionary<Menu_lists, Dictionary<Menu_lists, List<Menu_lists>>> dictionary = new Dictionary<Menu_lists, Dictionary<Menu_lists, List<Menu_lists>>>();
            ////读取全部
            //List<BsonDocument> list = collection.Find(builderFilter.Empty).ToList();


            var roleLiost = db.rolemenu.Where(x => !x.Delete).ToList();
            if (!string.IsNullOrWhiteSpace(roid))
            {
                roleLiost = roleLiost.Where(x => x.Roid.Contains(roid)).ToList();
            }

            List<rolemenu> viewrolemenu = new List<rolemenu>();
            foreach (var item in roleLiost)
            {
                if (item.ParentId == "0")
                {
                    foreach (var ite in roleLiost)
                    {
                        if (ite.ParentId == item.Roid)
                        {
                            item.children.Add(ite);
                        }
                    }
                    viewrolemenu.Add(item);
                }

            }
            //var  viewrolemenu
           //List<Data_tables> listDemo = new List<Data_tables>();

            //for (int i = 0; i < list.Count; i++)
            //{
            //    //一级菜单
            //    BsonDocument bsonDocument = list[i].AsBsonDocument;
            //    Data_tables Fathermenu = new Data_tables();
            //    Fathermenu._id = bsonDocument["_id"].ToString();
            //    Fathermenu.module = bsonDocument["module"].ToString();
            //    Fathermenu.describe = bsonDocument["describe"].ToString();
            //    Fathermenu.sqlstr = bsonDocument["sqlstr"].ToString();
            //    listDemo.Add(Fathermenu);
            //}
            //var data_tables_ids = string.Empty;
            //try
            //{
            //    var dataid = data_authority.Find(builderFilter.Eq("roid", roid)).FirstOrDefault();
            //    if (dataid != null) //不存在
            //    {

            //        data_tables_ids = dataid["data_tables_id"].ToString();
            //    }
            //    else
            //    {
            //        data_tables_ids = null;
            //    }

            //}
            //catch
            //{
            //    data_tables_ids = null;
            //}
            return new JsonResult(new { DicData = viewrolemenu });
        }







        [HttpGet("GetInitDatale")]
        public JsonResult GetInitDatale()
        {
            //var DicData = DictData();
            //List<Menu_lists> lists = new List<Menu_lists>();

            ////  var  dd=db.rolemenu.ToList();
            //try
            //{
            //    List<string> str = new List<string>();
            //    foreach (var item in DicData)
            //    {
            //        var Menu = new Menu_lists();
            //        Menu.Name = item.Key.Name;
            //        Menu.Url = item.Key.Url;
            //        Menu.Ico = item.Key.Ico;

            //        Menu.Roid = item.Key.Roid;
            //        GetBind(str, Menu.Roid);
            //        Menu.FatherRoid = item.Key.FatherRoid;

            //        //var dd1 = dd.Where(x => x.name.Equals(Menu.Name)).FirstOrDefault();
            //        //if (dd1 != null)
            //        //{
            //        //    dd1.Roid = Menu.Roid;
            //        //    dd1.index = Menu.Index;
            //        //    dd1.ParentId = Menu.FatherRoid;

            //        //    db.rolemenu.Update(dd1);
            //        //    db.SaveChanges();
            //        //}
            //        foreach (var itemkey in item.Value)
            //        {
            //            var MenuChlierd = new Menu_lists();
            //            MenuChlierd.Name = itemkey.Key.Name;
            //            MenuChlierd.Url = itemkey.Key.Url;
            //            MenuChlierd.Roid = itemkey.Key.Roid;
            //            MenuChlierd.FatherRoid = itemkey.Key.FatherRoid;
            //            GetBind(str, MenuChlierd.Roid);
            //            //var dd2 = dd.Where(x => x.name.Equals(MenuChlierd.Name)).FirstOrDefault();
            //            //if (dd2 != null)
            //            //{
            //            //    dd2.Roid = MenuChlierd.Roid;
            //            //    dd2.index = itemkey.Key.Index;
            //            //    dd2.ParentId = MenuChlierd.FatherRoid;
            //            //    db.rolemenu.Update(dd2);
            //            //    db.SaveChanges();
            //            //} 
            //            foreach (var itemkeytwo in itemkey.Value)
            //            {
            //                var MenuChlierdywo = new Menu_lists();
            //                MenuChlierdywo.Name = itemkeytwo.Name;
            //                MenuChlierdywo.Url = itemkeytwo.Url;
            //                MenuChlierdywo.Roid = itemkeytwo.Roid;
            //                MenuChlierdywo.FatherRoid = itemkeytwo.FatherRoid;
            //                Menu.children.Add(MenuChlierdywo);
            //                GetBind(str, MenuChlierdywo.Roid);
            //                //var dd3 = dd.Where(x => x.name.Equals(itemkeytwo.Name)).FirstOrDefault();
            //                //if (dd3 != null)
            //                //{
            //                //    dd3.Roid = MenuChlierdywo.Roid;
            //                //    dd3.index = itemkeytwo.Index;

            //                //    dd3.ParentId = MenuChlierdywo.FatherRoid;
            //                //    db.rolemenu.Update(dd3);
            //                //    db.SaveChanges();
            //                //} 
            //            }
            //            Menu.children.Add(MenuChlierd);
            //        }
            //        lists.Add(Menu);
            //    }
            //    //GYCTOAManagementSystemNewApi.Model.ViewModel.Menu_lists

            //}
            //catch (Exception ex)
            //{


            //}


            var roleLiost = db.rolemenu.Where(x => !x.Delete).ToList();
            List<rolemenu> viewrolemenu = new List<rolemenu>();
            foreach (var item in roleLiost)
            {
                if (item.ParentId == "0")
                {
                    item.children = roleLiost.Where(x => x.ParentId.Equals(item.Roid)).ToList();
                    foreach (var itemch in item.children)
                    {
                        itemch.children = roleLiost.Where(x => x.ParentId.Equals(itemch.Roid)).ToList();
                    }
                    viewrolemenu.Add(item);
                }
            }
            return new JsonResult(new { DicData = viewrolemenu });
        }

        private void GetBind(List<string> strlist, string str)
        {
            if (strlist.Contains(str))
            {

            }
            else
            {
                strlist.Add(str);
            }

        }
        private List<BsonDocument> GetListBsonDocument()
        {
            //查询权限列表
            //读取mongodb数据库 查询权限值拥有的菜单
            string strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:mongo_con");
            var client = new MongoClient(strcon);
            var clientdb = client.GetDatabase("oalist");
            //读取集合collection
            var collection = clientdb.GetCollection<BsonDocument>("menu_lists");
            //创建约束生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //读取全部
            return collection.Find(builderFilter.Empty).ToList();

        }

        //将整个MongoDB的数据封装成方法
        private Dictionary<Menu_lists, Dictionary<Menu_lists, List<Menu_lists>>> DictData()
        {

            Dictionary<Menu_lists, Dictionary<Menu_lists, List<Menu_lists>>> dictionary = new Dictionary<Menu_lists, Dictionary<Menu_lists, List<Menu_lists>>>();
            //读取全部

            List<BsonDocument> list = GetListBsonDocument();
            for (int i = 0; i < list.Count; i++)
            {

                //一级菜单
                BsonDocument bsonDocument = list[i].AsBsonDocument;
                Menu_lists Fathermenu = new Menu_lists();
                Fathermenu.FatherRoid = "无";
                Fathermenu.Name = bsonDocument["name"].AsString;
                Fathermenu.Roid = bsonDocument["roid"].AsString;
                Fathermenu.Ico = bsonDocument["ico"].AsString;
                Fathermenu.Index = bsonDocument["index"].AsInt32;

                //二级菜单
                Dictionary<Menu_lists, List<Menu_lists>> menuListses = new Dictionary<Menu_lists, List<Menu_lists>>();
                if (list[i].Contains("role"))
                {
                    if (list[i]["role"].IsBsonArray)
                    {
                        var lisArray = list[i]["role"].AsBsonArray;
                        for (int j = 0; j < lisArray.Count; j++)
                        {

                            BsonDocument str = lisArray[j].AsBsonDocument;
                            Menu_lists menu = new Menu_lists();
                            menu.FatherRoid = bsonDocument["roid"].AsString;
                            menu.Roid = str["roid"].AsString;
                            menu.Url = str["url"].AsString;
                            menu.Name = str["name"].AsString;
                            var ddd = Convert.ToInt32(str["index"]);
                            menu.Index = Convert.ToInt32(ddd);


                            //三级菜单
                            List<Menu_lists> menulist = new List<Menu_lists>();
                            if (str.Contains("role"))
                            {
                                if (str["role"].IsBsonArray)
                                {
                                    var threeArray = str["role"].AsBsonArray;
                                    for (int k = 0; k < threeArray.Count; k++)
                                    {
                                        BsonDocument threestr = threeArray[k].AsBsonDocument;
                                        Menu_lists threemenu = new Menu_lists();
                                        threemenu.Roid = threestr["roid"].AsString;
                                        threemenu.Name = threestr["name"].AsString;
                                        threemenu.Index = 0;
                                        menulist.Add(threemenu);

                                    }

                                }
                                else
                                {
                                    var threeArray = str["role"].AsBsonDocument;
                                    BsonDocument threestr = threeArray;
                                    Menu_lists threemenu = new Menu_lists();
                                    threemenu.Roid = threestr["roid"].AsString;
                                    threemenu.Name = threestr["name"].AsString;
                                    threemenu.Index = 0;
                                    menulist.Add(threemenu);

                                };
                            }
                            menuListses.Add(menu, menulist);

                        }
                    }
                    else
                    {
                        BsonDocument lisArray = list[i]["role"].AsBsonDocument;
                        Menu_lists menu = new Menu_lists();
                        menu.FatherRoid = lisArray["roid"].AsString;
                        menu.Roid = lisArray["roid"].AsString;
                        menu.Url = lisArray["url"].AsString;
                        menu.Name = lisArray["name"].AsString;
                        menu.Index = lisArray["index"].AsInt32;
                        if (lisArray.Contains("role"))
                        {
                            //三级菜单
                            List<Menu_lists> menulist = new List<Menu_lists>();
                            if (lisArray["role"].IsBsonArray)
                            {
                                var BDlisArray = lisArray["role"].AsBsonArray;
                                for (int j = 0; j < BDlisArray.Count; j++)
                                {
                                    BsonDocument threestr = BDlisArray[j].AsBsonDocument;
                                    Menu_lists threemenu = new Menu_lists();
                                    threemenu.Roid = threestr["roid"].AsString;
                                    threemenu.Name = threestr["name"].AsString;
                                    threemenu.Index = 0;
                                    menulist.Add(threemenu);

                                }
                            }
                            else
                            {
                                BsonDocument bd = lisArray["role"].AsBsonDocument;
                                BsonDocument threestr = bd;
                                Menu_lists threemenu = new Menu_lists();
                                threemenu.Roid = threestr["roid"].AsString;
                                threemenu.Name = threestr["name"].AsString;
                                threemenu.Index = 0;
                                menulist.Add(threemenu);

                            }
                            menuListses.Add(menu, menulist);
                        }
                        else
                        {
                            menuListses.Add(menu, null);
                        }

                    }
                }
                dictionary.Add(Fathermenu, menuListses);
            }
            return dictionary;

        }
        #endregion

        #region 模块管理
        /// <summary>
        /// 添加模块数据
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("AddModule")]
        public JsonResult AddModule([FromBody] dynamic formData)
        {
            //Menu_lists menu
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var menu = JsonConvert.DeserializeObject<Menu_lists>(jsondata["role"].ToString());
            var sRoid = db.rolemenu.Where(x => !x.Delete&&x.Roid.Equals(menu.Roid)).FirstOrDefault();
            if (sRoid != null)
            {
                return new JsonResult(new { succeed = false });
            }
            else
            {
                rolemenu filter = new rolemenu();
                try
                {
                    
                    filter.Roid = menu.Roid;
                    filter.url = menu.Url;
                    filter.ico = menu.Ico;
                    filter.ParentId = menu.FatherRoid;
                    filter.name = menu.Name.Trim();
                    filter.Delete = false;
                    filter.index = db.rolemenu.Where(x => !x.Delete && x.ParentId.Equals(menu.FatherRoid)).ToList().Count;
                    db.Entry<rolemenu>(filter).State =EntityState.Added;
                    db.rolemenu.Add(filter);
                    return new JsonResult(new { succeed = db.SaveChanges() > 0 });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                return new JsonResult(new { succeed = false });
            }
        }

        /// <summary>
        /// 修改目录数据
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("UpdateModule")]
        public JsonResult UpdateModule([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var uprole = JsonConvert.DeserializeObject<rolemenu>(jsondata["role"].ToString());
            var upser = db.rolemenu.Where(x => x.Id.Equals(uprole.Id)).FirstOrDefault();
            var biit = true;
            if (upser.Roid != uprole.Roid)
            {
                var sRoid = db.rolemenu.Where(x => x.Roid.Equals(uprole.Roid)).FirstOrDefault();
                if (sRoid!=null)
                {
                    biit = false;
                }
            }
            if (biit)
            {
                upser.ico = uprole.ico;
                upser.name = uprole.name;
                upser.url = uprole.url;
                upser.Roid = uprole.Roid;

                var bit = db.SaveChanges() > 0;
                return new JsonResult(new { succeed = bit });
            }
            else
            {
                return new JsonResult(new { succeed = false });
            }



            ////读取mongodb数据库 查询权限值拥有的菜单
            //string strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:mongo_con");
            //MongoClient client = new MongoClient(strcon);
            //var clientdb = client.GetDatabase("oalist");
            ////读取集合collection
            //var collection = clientdb.GetCollection<BsonDocument>("menu_lists");
            //FilterDefinition<BsonDocument> filter = null;

            //if (menu.FatherRoid != "无")
            //{
            //    filter = Builders<BsonDocument>.Filter.Eq("role.roid", menu.Roid);
            //    var roles = collection.Find(filter).FirstOrDefault();
            //    List<BsonDocument> bds = new List<BsonDocument>();

            //    for (int i = 0; i < roles["role"].AsBsonArray.Count; i++)
            //    {
            //        if (roles["role"][i]["roid"].AsString == menu.Roid)
            //        {
            //            roles["role"][i]["name"] = menu.Name.Trim();
            //            roles["role"][i]["url"] = menu.Url;
            //            roles["role"][i]["ico"] = menu.Ico == null ? "" : menu.Ico;
            //        }
            //        bds.Add(roles["role"][i].AsBsonDocument);
            //    }
            //    var update = Builders<BsonDocument>.Update.Set("role", bds);
            //    var result = collection.UpdateOne(filter, update);
            //    if (result.MatchedCount == 1)
            //    {
            //        return new JsonResult(new { succeed = true });
            //    }
            //    else
            //    {
            //        return new JsonResult(new { succeed = false });
            //    }
            //}
            //else
            //{
            //    filter = Builders<BsonDocument>.Filter.Eq("roid", menu.Roid);
            //    UpdateDefinition<BsonDocument> update = Builders<BsonDocument>.Update.Set("name", menu.Name.Trim()).Set("ico", menu.Ico.Trim());
            //    BsonDocument bd = collection.Find(filter).ToBsonDocument();
            //    var result = collection.UpdateOne(filter, update);

            //    if (result.MatchedCount == 1)
            //    {
            //        return new JsonResult(new { succeed = true });
            //    }
            //    else
            //    {
            //        return new JsonResult(new { succeed = false });
            //    }
            //}
        }

        /// <summary>
        /// 删除列表数据
        /// </summary>
        /// <param name="Roid"></param>
        /// <param name="FatherRoid"></param>
        /// <returns></returns>
        [HttpGet("DeleModule")]
        public JsonResult DeleModule(string Roid)
        {
            var role = db.rolemenu.Where(x => !x.Delete && x.Roid.Equals(Roid)).FirstOrDefault();
            var bit = false;
            if (role != null)
            {
                role.Delete = true;
                bit = db.SaveChanges() > 0;
            }
            return new JsonResult(new { succeed = bit });

            ////读取mongodb数据库 查询权限值拥有的菜单
            //string strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:mongo_con");
            //MongoClient client = new MongoClient(strcon);
            //var clientdb = client.GetDatabase("oalist");
            ////读取集合collection
            //var collection = clientdb.GetCollection<BsonDocument>("menu_lists");
            //if (FatherRoid != "无")
            //{
            //    FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.Eq("role.roid", Roid);
            //    var roles = collection.Find(filter).FirstOrDefault();
            //    if (roles == null)
            //    {
            //        return new JsonResult(new { succeed = false });
            //    }
            //    BsonDocument bd = new BsonDocument();
            //    if (roles["role"].IsBsonArray)
            //    {
            //        for (int i = 0; i < roles["role"].AsBsonArray.Count; i++)
            //        {
            //            if (roles["role"][i]["roid"].AsString == Roid)
            //            {
            //                bd = roles["role"][i].AsBsonDocument;
            //                break;
            //            }
            //        }
            //        var update = Builders<BsonDocument>.Update.Pull("role", bd);
            //        var result = collection.UpdateOne(filter, update);
            //        if (result.MatchedCount == 1)
            //        {
            //            return new JsonResult(new { succeed = true });
            //        }
            //        else
            //        {
            //            return new JsonResult(new { succeed = false });
            //        }
            //    }
            //    else
            //    {
            //        var update = Builders<BsonDocument>.Update.Unset("role");
            //        var result = collection.UpdateOne(filter, update);
            //        if (result.MatchedCount == 1)
            //        {
            //            return new JsonResult(new { succeed = true });
            //        }
            //        else
            //        {
            //            return new JsonResult(new { succeed = false });
            //        }
            //    }


            //}
            //else
            //{
            //    FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.Eq("roid", Roid);
            //    var result = collection.DeleteOne(filter);
            //    if (result.DeletedCount == 1)
            //    {
            //        return new JsonResult(new { succeed = true });
            //    }
            //    else
            //    {
            //        return new JsonResult(new { succeed = false });
            //    }
            //}
        }

      //权限模块结束 2021年6月16日14:35:07
        #endregion
    }

}
